package com.czk.saatext2image.controller;

import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.util.UUID;

/**
 * @Author: chenzhangkun
 * @CreateTime: 2025-10-21
 * @Description:
 * @Version: 1.0
 */
@RestController
public class Text2VoiceController {
    @Resource
    private SpeechSynthesisModel speechSynthesisModel;
    /**
     * s生成图片的模型
     */
    private static final String VOICE_MODEL = "cosyvoice-v2";
    /**
     * 音色
     */
    private static final String BAILIAN_VOICE_TIMER = "longyingcui";

    /**
     * 会生成图片url
     *
     * @param prompt
     * @return
     */
    @GetMapping(value = "/text2voice")
    public String voice(@RequestParam(name = "prompt", defaultValue = "我为什么不能去喝酒") String prompt) {
        String filePath = "d:\\" + UUID.randomUUID() + ".mp3";

        DashScopeSpeechSynthesisOptions dashScopeSpeechSynthesisOptions = DashScopeSpeechSynthesisOptions.builder()
                .model(VOICE_MODEL)
                .voice(BAILIAN_VOICE_TIMER)
                .build();
        SpeechSynthesisResponse speechSynthesisResponse = speechSynthesisModel.call(new SpeechSynthesisPrompt(prompt, dashScopeSpeechSynthesisOptions));
        // 字节流语音转换
        ByteBuffer byteBuffer = speechSynthesisResponse.getResult().getOutput().getAudio();
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(byteBuffer.array());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return filePath;
    }
}
